package com.example.shardingjdbcdemo.config;

import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;

public class OrderComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm<String> {

    public OrderComplexKeysShardingAlgorithm() {
        System.out.println("=============OrderComplexKeysShardingAlgorithm");
    }


    /**
     * 分片
     *
     * @param collection               表名称 t_order_0 t_order_1 t_order_2 t_order_3
     * @param complexKeysShardingValue 原表名称t_order 分片列名称 order_seq buyer_id
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<String> complexKeysShardingValue) {

        System.out.println("=============doSharding");
        //返回使用的表名称
        Collection<String> result = new HashSet<>();
        String logicTableName = complexKeysShardingValue.getLogicTableName();
        // map存储的 order_seq buyer_id 的值 分片的字段
        Map<String, Collection<String>> columnNameAndShardingValuesMap = complexKeysShardingValue.getColumnNameAndShardingValuesMap();
        //存在买家id 按照买家分片
        Collection<String> columnValues = columnNameAndShardingValuesMap.get("buyer_id");
        if (!isEmpty(columnValues)) {
            for (String columnValue : columnValues) {
                String tableName = getTableName(logicTableName, columnValue);
                result.add(tableName);
            }
            return result;
        }
        // 不存在的时候如何处理 其实就是订单号
        columnNameAndShardingValuesMap.forEach((k, otherColumnValues) -> {
            for (String otherColumnValue : otherColumnValues) {
                String tableName = getTableName(logicTableName, otherColumnValue);
                result.add(tableName);
            }
        });
        return result;
    }

    private boolean isEmpty(Collection<String> columnValues) {
        return columnValues == null || columnValues.size() == 0;
    }

    /**
     * 获取表名称 分片数量也可以动态设置，这里写死了分4张表
     *
     * @param logicTableName
     * @param columnValue
     * @return
     */
    private String getTableName(String logicTableName, String columnValue) {
        return logicTableName + "_" + (Math.abs(columnValue.hashCode()) % 4);
    }
}
